package com.fit.spring.boot.mapper.autoconfigure;

import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.core.env.Environment;

import tk.mybatis.mapper.mapperhelper.MapperHelper;
import tk.mybatis.mapper.util.StringUtil;
import tk.mybatis.spring.mapper.MapperFactoryBean;


/**
 * mapper自动装配处理器
 * @author hcl
 *
 */
public class MapperAutoConfigurationProcessor implements BeanDefinitionRegistryPostProcessor{

	private static Logger log = LoggerFactory.getLogger(MapperAutoConfigurationProcessor.class);
	
	/**
	 * 配置对象
	 */
	private Environment environment;
	
	
	/**
	 * BeanDefinition后置处理器,对mapper进行特殊处理
	 */
	@Override
	public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
		
		Properties properties = new MapperProperties(environment).getProperties();
		if(log.isDebugEnabled()){
			log.debug("加载通用的mapper配置：{}",properties.toString());
		}
		
		
		MapperHelper mapperHelper = new MapperHelper();
		if(properties != null){
			mapperHelper.setProperties(properties);
		}
		//如果没有注册过接口，就注册默认的Mapper接口
        mapperHelper.ifEmptyRegisterDefaultInterface();
        String[] names = registry.getBeanDefinitionNames();
        GenericBeanDefinition definition;
        for (String name : names) {
            BeanDefinition beanDefinition = registry.getBeanDefinition(name);
            if (beanDefinition instanceof GenericBeanDefinition) {
                definition = (GenericBeanDefinition) beanDefinition;
                if (StringUtil.isNotEmpty(definition.getBeanClassName())
                        && definition.getBeanClassName().equals("org.mybatis.spring.mapper.MapperFactoryBean")) {
                    definition.setBeanClass(MapperFactoryBean.class);
                    definition.getPropertyValues().add("mapperHelper", mapperHelper);
                }
            }
        }
	}

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
	}

	
	
	/**
	 * 构造属性注入
	 * @param propertes
	 */
	public MapperAutoConfigurationProcessor(Environment environment) {
		this.environment = environment;
	}

}
